package com.cse.engine.subEngine;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.cse.mvc.models.Result;
import com.cse.utils.Util;
import com.mutear.ParallelSearcher.utils.IResult;

public class SogouEngine extends BaseEngine {
	
	public SogouEngine() {
		super("Sogou");
	}

	@Override
	protected List<IResult> handleHtml(String html) {
		List<IResult> results = new ArrayList<IResult>();
		if (html == null || html.length() == 0)
			return null;
		Document doc = Jsoup.parse(html);
		Elements eles = doc.select("div.vrwrap");
		int i = 0;
		for(Element ele : eles){
			String title = null, url = null, summary = null;
			
			Elements elements = ele.select("h3>a");
			if(elements.size() != 0){
				title = elements.first().text();
				if(null == title || title.length() == 0) continue;
			}
			else{
				continue;
			}
			String href = null;
			href = elements.first().attr("href");
			url = href;
			if(null == url || url.length() == 0) continue;
			elements = ele.select("p");
			if(elements.size() != 0){
				summary = elements.first().text();
			}
			
			Result result = new Result(title, url, summary, engineName);
			results.add(result);
			
			i++;
			if(i >= Util.EACH_ENGINE_RETURN_NUM) break;
		}
		
		return results;
	}

	@Override
	protected String perfectUrl(String key) {
		return Util.SOGOU_PRE_URL + convert(key) + Util.SOGOU_SUFFIX_URL;
	}

}
